package com.oly.cms.web.utils;

import java.io.File;
import java.io.FileNotFoundException;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.MediaType;
import com.grace.common.enums.GraceServerRoot;
import com.grace.common.utils.file.FileUtils;
import com.grace.oss.domain.OlyOss;
import com.oly.cms.common.utils.ZipUtils;

public class WebUtils {

    private static final Logger log = LoggerFactory.getLogger(WebUtils.class);

    /**
     * 删除主题
     * 
     * @param themeName
     * @return
     * @throws FileNotFoundException
     */
    public static boolean deleteThemeFile(String themeName) throws FileNotFoundException {
        // 删除模板 xx/server/themes/olyCode/templates/主题名字
        // 删除静态资源 xx/server/themes/olyCode/static/主题名字
        File templatesFile = Paths
                .get(GraceServerRoot.THEME_DIR.getWorkRoot(GraceServerRoot.THEME_TEMPLATE_DIR.getValue()), themeName)
                .toFile();

        File staticFile = Paths
                .get(GraceServerRoot.THEME_DIR.getWorkRoot(GraceServerRoot.THEME_STATIC_DIR.getValue()), themeName)
                .toFile();
        ;
        if (templatesFile.exists()) {
            if (!deleteDir(templatesFile)) {
                return false;
            }
        }
        if (templatesFile.exists()) {
            return deleteDir(staticFile);
        }
        return true;
    }

    /**
     * 递归删除目录下的所有文件及子目录下所有文件
     * 
     * @param dir 将要删除的文件目录
     * @return boolean Returns "true" if all deletions were successful. If a
     *         deletion fails, the method stops attempting to delete and returns
     *         "false".
     */
    private static boolean deleteDir(File dir) {
        if (dir.isDirectory()) {
            String[] children = dir.list();
            // 递归删除目录中的子目录下
            for (int i = 0; i < children.length; i++) {
                boolean success = deleteDir(new File(dir, children[i]));
                if (!success) {
                    return false;
                }
            }
        }
        // 目录此时为空，可以删除
        return dir.delete();
    }

    /**
     * 获取本地主题列表
     * 
     * @return
     */
    public static List<String> listThemeNames() {
        File f = Paths.get(GraceServerRoot.THEME_DIR.getWorkRoot(GraceServerRoot.THEME_TEMPLATE_DIR.getValue()))
                .toFile();
        if (f.exists() && f.isDirectory()) {
            File[] files = f.listFiles();
            List<String> listThemeNames = new ArrayList<>();
            for (File file : files) {
                if (file.isDirectory()) {
                    listThemeNames.add(file.getName());
                }
            }
            return listThemeNames;
        }
        return null;
    }

    /**
     * 获取备份
     * 
     * @return
     */
    public static List<OlyOss> listBackThemes() {
        File f = Paths.get(GraceServerRoot.BACK_DIR.getWorkRoot(GraceServerRoot.THEME_DIR.getValue())).toFile();
        List<OlyOss> listThemes = new ArrayList<>();
        if (f.exists() && f.isDirectory()) {
            File[] files = f.listFiles();
            for (File file : files) {
                if (!file.isDirectory()) {
                    OlyOss olyOss = new OlyOss();
                    olyOss.setFileName(file.getName());
                    olyOss.setUpdateTime(new Date(file.lastModified()));
                    olyOss.setSize(file.length());
                    listThemes.add(olyOss);
                }
            }
        }
        return listThemes;
    }

    /**
     * 主题备份
     * 
     * @param themeName
     */
    public static void backUpTheme(String themeName) {
        // String backPath =
        // Paths.get(GraceServerRoot.THEME_DIR.getOnlyCodeRoot(themeName)).toString();
        // String savePath =
        // Paths.get(GraceServerRoot.BACK_DIR.getOnlyCodeRoot(GraceServerRoot.THEME_DIR.getValue()),
        // themeName + "_" + DateUtils.dateTimeNow() + ".zip").toString();
        // ZipUtils.themeToZip(backPath, savePath, true);
    }

    /** 删除主题 */
    public static void removeBackTheme(String themeName) {
        File file = Paths.get(GraceServerRoot.BACK_DIR.getWorkRoot(GraceServerRoot.THEME_DIR.getValue()), themeName)
                .toFile();
        ZipUtils.deleteDir(file);

    }

    public static void downloadBackTheme(String themeName, HttpServletResponse response, HttpServletRequest request) {
        try {
            String filePath = Paths
                    .get(GraceServerRoot.BACK_DIR.getWorkRoot(GraceServerRoot.THEME_DIR.getValue()), themeName)
                    .toString();
            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            FileUtils.setAttachmentResponseHeader(response, themeName);
            FileUtils.writeBytes(filePath, response.getOutputStream());
        } catch (Exception e) {
            log.error("下载文件失败", e);
        }
    }

}
